<?php


function file_upload($file, $type = 'image', $name = '') {

    $harmtype = array('asp', 'php', 'jsp', 'js', 'css', 'php3', 'php4', 'php5', 'ashx', 'aspx', 'exe', 'cgi');
    if (empty($file)) {
        return error(-1, '没有上传内容');
    }
    if (!in_array($type, array('image', 'thumb', 'voice', 'video', 'audio'))) {
        return error(-2, '未知的上传类型');
    }
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $ext = strtolower($ext);
    switch ($type) {
        case 'image' :
        case 'thumb' :
            $allowExt = array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'ico');
            $limit = 6*1024;
            break;
        case 'voice' :
        case 'audio' :
            $allowExt = array('mp3', 'wma', 'wav', 'amr');
            $limit = 6*1024;
            break;
        case 'video' :
            $allowExt = array('rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4');
            $limit = 6*1024;
            break;
    }

    if (!in_array(strtolower($ext), $allowExt) || in_array(strtolower($ext), $harmtype)) {
        return error(-3, '不允许上传此类文件');
    }
    if (!empty($limit) && $limit * 1024 < filesize($file['tmp_name'])) {
        return error(-4, "上传的文件超过大小限制，请上传小于 {$limit}k 的文件");
    }
    $result = array();
    if (empty($name) || $name == 'auto') {
        $path = "{$type}s/" . date('Y/m/');
        mkdirs(ATTACHMENT_ROOT . '/' . $path);
        $filename = file_random_name(ATTACHMENT_ROOT . '/' . $path, $ext);        
        $result['path'] = $path . $filename;
    } else {
        mkdirs(dirname(ATTACHMENT_ROOT . '/' . $name));
        if (!strexists($name, $ext)) {
            $name .= '.' . $ext;
        }
        $result['path'] = $name;
    }
    
    if (!file_move($file['tmp_name'], ATTACHMENT_ROOT . '/' . $result['path'])) {
        return error(-1, '保存上传文件失败');
    }
    $result['success'] = true;
    return $result;
}


function file_move($filename, $dest) {
    mkdirs(dirname($dest));
    if (is_uploaded_file($filename)) {
        move_uploaded_file($filename, $dest);
    } else {
        rename($filename, $dest);
    }
    @chmod($filename, 0777);
    return is_file($dest);
}


function array_elements($keys, $src, $default = FALSE) {
    $return = array();
    if(!is_array($keys)) {
        $keys = array($keys);
    }
    foreach($keys as $key) {
        if(isset($src[$key])) {
            $return[$key] = $src[$key];
        } else {
            $return[$key] = $default;
        }
    }
    return $return;
}



function sizecount($size) {
    if($size >= 1073741824) {
        $size = round($size / 1073741824 * 100) / 100 . ' GB';
    } elseif($size >= 1048576) {
        $size = round($size / 1048576 * 100) / 100 . ' MB';
    } elseif($size >= 1024) {
        $size = round($size / 1024 * 100) / 100 . ' KB';
    } else {
        $size = $size . ' Bytes';
    }
    return $size;
}

function file_random_name($dir, $ext) {
    do {
        $filename = random(30) . '.' . $ext;
    } while (file_exists($dir . $filename));
    
    return $filename;
}



function random($length, $numeric = FALSE) {
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    if ($numeric) {
        $hash = '';
    } else {
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
    }
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}


if(!function_exists("strexists"))
{
    function strexists($string, $find) {
        return !(strpos($string, $find) === FALSE);
    }    
}

function is_error($data) {
    if (empty($data) || !is_array($data) || !array_key_exists('errno', $data) || (array_key_exists('errno', $data) && $data['errno'] == 0)) {
        return false;
    } else {
        return true;
    }
}

function file_delete(){
    if (empty($file)) {
        return FALSE;
    }
    if (file_exists($file)) {
        @unlink($file);
    }
    return TRUE;
}

function message($msg, $redirect = '', $type = '', $tips = false) {

    if($redirect == 'refresh') {
        $redirect =  $_SERVER['QUERY_STRING'];
    }
    if($redirect == 'referer') {
        $redirect = referer();
    }
    if($redirect == '') {
        $type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'info';
    } else {
        $type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'success';
    }
    if ( !empty($_GET['isajax']) || $type == 'ajax') {
        if($type != 'ajax' && !empty($_REQUEST['target'])) {
            exit("
<script type=\"text/javascript\">
    var url = ".(!empty($redirect) ? 'parent.location.href' : "''").";
    var modalobj = util.message('".$msg."', '', '".$type."');
    if (url) {
        modalobj.on('hide.bs.modal', function(){\$('.modal').each(function(){if(\$(this).attr('id') != 'modal-message') {\$(this).modal('hide');}});top.location.reload()});
    }
</script>");
        } else {
            $vars = array();
            $vars['message'] = $msg;
            $vars['redirect'] = $redirect;
            $vars['type'] = $type;
            exit(json_encode($vars));
        }
    }
    if (empty($msg) && !empty($redirect)) {
        header('Location: '.$redirect);
        exit;
    }
    $label = $type;
    if($type == 'error') {
        $label = 'danger';
    }
    if($type == 'ajax' || $type == 'sql') {
        $label = 'warning';
    }
    
    if ($tips) {
        if (is_array($msg)){
            $message_cookie['title'] = 'MYSQL 错误';
            $message_cookie['msg'] = 'php echo cutstr(' . $msg['sql'] . ', 300, 1);';
        } else{
            $message_cookie['title'] = $caption;
            $message_cookie['msg'] = $msg;
        }
        $message_cookie['type'] = $label;
        $message_cookie['redirect'] = $redirect ? $redirect : referer();
        $message_cookie['msg'] = rawurlencode($message_cookie['msg']);
        
        isetcookie('message', stripslashes(json_encode($message_cookie, JSON_UNESCAPED_UNICODE)));
        if (!empty($message_cookie['redirect'])) {
            header('Location: ' . $message_cookie['redirect']);
        } else {
            include template('common/message', TEMPLATE_INCLUDEPATH);
        }
    } else {
        include template('common/message', TEMPLATE_INCLUDEPATH);
    }
    exit;
}


